package models

import (
	"github.com/astaxie/beego/orm"
	"fmt"
	"time"
	"errors"
)

type HitdicProject struct {
	Id       int          `json:"id"`
	Uid     *User `json:"user" orm:"rel(fk)"`
    Title    string       `json:"title"`
	Created  time.Time  `json:"created" orm:"auto_now_add;type(datetime)"`
    Updated          time.Time `json:"updated" orm:"auto_now_add;type(datetime)"`
	SimInput string `json:"siminput"`
	OpInput string `json:"opinput"`
	DbInput string `json:"dbinput"`
    ExpDatas []*ExpData   `orm:"reverse(many)"` //反向一对多关联
}

type ExpData struct {
	Id      int      `json:"id"`
	Title string  `json:"title"`
	Created          time.Time  `json:"created" orm:"auto_now_add;type(datetime)"`
	Updated          time.Time `json:"updated" orm:"auto_now_add;type(datetime)"`
	Content string `json:"content"`
	Hid     *HitdicProject `json:"hitdicproject" orm:"rel(fk)"`
}

func init() {
	orm.RegisterModel(new(HitdicProject), new(ExpData))
}

func AddHitdicProject(project HitdicProject) (int, error) {
	o := orm.NewOrm()
	o.Using("default")
	project.Created = time.Now()
	fmt.Println(o.Insert(&project));
	
	return project.Id, nil
}

func GetHitdicProject(pid int) (*HitdicProject, error) {
	o := orm.NewOrm()
	pro := HitdicProject{Id: pid}
	err := o.Read(&pro)
	
	if err != nil {
		return &HitdicProject{Id: -1}, errors.New("Fail to find the project")
	}
	return &pro, nil
}

func GetAllHitdicProjects() []*HitdicProject {
	o := orm.NewOrm()
	var pros []*HitdicProject
	_, err := o.QueryTable("hitdicproject").All(&pros)
	if err != nil {
		return []*HitdicProject{}
	}
	return pros
}
